<?php

include 'BaseDaoImpl.php';
class MySQLDaoImpl extends BaseDaoImpl{
	private $conn;
	
     /**
	 * @param $configFilePath 配置文件路径
	 */
	function __construct($configFilePath){
		parent::__construct($configFilePath);
	}
	public function openConn(){
		//打开数据库连接
		$conn=mysql_connect($this->db_host.":".$this->db_port,$this->db_user,$this->db_pwd,true) 
		or die("Unable to connect to the MySQL!");
		$this->conn=$conn;
		//选择数据库
	    mysql_select_db($this->db_name,$this->conn);
		return $conn;
	}
	public function closeConn(){
		mysql_close($this->conn);
	}
	
	/**
	 * mysql中获得所有记录数,
	 * 例如:$array[0]表示第一条记录,$array[0]['id']表示id字段
	 * @return Array 记录总数，每条记录为数组，索引为字段名,
	 * 注意：字段名区分大小写
	 */
	public function queryAll($query){
		//打开数据库连接
		$this->conn=$this->openConn();
		//编译sql语句
		$statement=mysql_query($query,$this->conn);
		if($statement==false){
			die(mysql_error($this->conn));
		}
		//获得结果
		$records=Array();
		while($result=mysql_fetch_array($statement,MYSQL_ASSOC)){
			array_push($records, $result);
		}

		//关闭数据库连接
		$this->closeConn();
		return $records;
	}
	
	/**
	 * 获得记录总数
	 */
	public function count($query){
		//打开数据库连接
		$this->conn=$this->openConn();
		//编译sql语句
		$statement=mysql_query($query,$this->conn);
		if($statement==false){
			die(mysql_error($this->conn));
		}
		$result=mysql_fetch_array($statement);
		//关闭数据库连接
		$this->closeConn();
		return $result[0];
	}
	
	public function save($query){
		//打开数据库连接
		$this->conn=$this->openConn();
		//编译sql语句
		$statement=mysql_query($query,$this->conn);
		if($statement==false){
			die(mysql_error($this->conn));
		}
		//关闭数据库连接
		$this->closeConn();
		return $statement;
	}
	
	/**
	 * 执行写操作
	 */
	public function execute($query){
		//打开数据库连接
		$this->conn=$this->openConn();
		//编译sql语句
		$statement=mysql_query($query,$this->conn);
		if($statement==false){
			//die(mysql_error($this->conn).getMessage());
			throw new Exception(mysql_error($this->conn));
		}
		//关闭数据库连接
		$this->closeConn();
		return $statement;
	}
}
?>